import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

class MyThreadPool {
    BlockingQueue<Runnable> queue = null;

    public MyThreadPool(int n) {
        queue = new ArrayBlockingQueue<>(1000);

        //创建n个线程
        for (int i = 0; i < n; i++) {
            Thread thread = new Thread(() -> {
                while (true) {
                    try {
                        Runnable task = queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

//            thread.setDaemon(true);//将thread设置为后台线程，当全部线程执行完后，程序自动结束
            thread.start();
        }
    }

    //将任务放入队列中
    public void submit(Runnable task) throws InterruptedException {
        this.queue.put(task);
    }
}

public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(10);//线程池中有10个线程

        for (int i = 0; i < 10000; i++) {
            int id = i;
            myThreadPool.submit(() -> {
                System.out.println(Thread.currentThread().getName() + " i = " + id);
            });
        }

    }
}
